<script lang="ts" setup>
	import common from '@/api/common.js'
	import {
		reactive,
		inject,
		ref,
		computed
	} from 'vue'
	import {
		useStore
	} from 'vuex'
	import {
		onLoad, onShow, onUnload, onBackPress
	} from '@dcloudio/uni-app'
	import dateTime from '@/static/js/date.js'
	interface obj {
		[propName : string] : any;
	}
	const store = useStore()
	const socket : any = inject("$socket");
	let voiceTimer : any = ref(0)
	let voiceShow = ref(false)
	let timer = null
	let clientY = reactive({
		moveY: 0,
		startY: 0
	})
	//#ifdef APP-PLUS
	const recorderManager : any = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	// #endif
	let gather : any = reactive({
		inputStyle: {
			"background": "#fff",
			"border-radius": "40rpx"
		},
		sendMsg: '',
		scrollTop: 0,
		scrollToView: '',
		isLoading: false,
		scrollAnimation: false,
		messageList: [],
		menberList: [],
		imgArr: [],
		emoji: {
			list: [],
			emojiPage: 1,
			emojiTotal: 0,
			swiperSize: 1,
			swiperCurrent: 0
		},
		userinfo: {},//接收者
		selfInfo: uni.getStorageSync('userinfo'),//自己的
		latestMinute: null
	})
	//动态padding
	let emojiPop = ref(false)
	let voicePop = ref(false)

	let current : any = ref(0) //预览当前页
	//获取表情包
	const getEmo = async (page : number, pageSize : number) => {
		const res = await common.emoji(page, pageSize)
		gather.emoji.list = res.data
		gather.emoji.emojiTotal = res.total
		gather.emoji.swiperSize = res.swiperSize
	}
	//滚动到顶部/左边
	const loadHistory = () => {

	}
	//点击抽屉
	const onPop = (type : number) => {
		//初始化
		if (type === 1) {
			voicePop.value = !voicePop.value
			emojiPop.value = false
		} else if (type === 4) {
			emojiPop.value = !emojiPop.value
			voicePop.value = false
		} else {
			emojiPop.value = false
			voicePop.value = false
		}
	}
	//预览
	const preview = (img : String) => {
		for (let i in gather.imgArr) {
			if (gather.imgArr[i] === img) {
				current.value = i
			}
		}
		uni.previewImage({
			urls: gather.imgArr,
			current: Number(current.value),
			longPressActions: {
				itemList: ['发送给朋友', '保存图片', '收藏'],
				success: function (data) {
					console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
				},
				fail: function (err) {
					console.log(err.errMsg);
				}
			}
		});
	}

	const onEmoji = (item : String) => {
		gather.sendMsg = gather.sendMsg.concat(item)
	}
	const listSwitch = (e) => {
		if (!e.detail.current) return
		getEmo(e.detail.current, 80)
	}

	//录音
	const touchstart = (e : obj) => {
		clientY.startY = e.changedTouches[0].clientY
		clientY.moveY = e.changedTouches[0].clientY
		voiceShow.value = true
		recorderManager.start()
		timer = setInterval(() => {
			voiceTimer.value++
			if (voiceTimer.value > 10) {
				touchend()
			}
		}, 1000)
	}
	const touchend = () => {
		voiceShow.value = false
		recorderManager.stop();
		clearInterval(timer)
		if ((clientY.startY - clientY.moveY) > 300) {
			return uni.showToast({
				title: '取消成功',
				icon: 'none',
				success: () => {
					voiceTimer.value = 0
					clientY.moveY = 0
				}
			})
		}

		if (voiceTimer.value < 2) {
			return uni.showToast({
				title: '按键时间太短',
				icon: 'none',
				success: () => {
					voiceTimer.value = 0
					clientY.moveY = 0
				}
			})
		}
		recorderManager.onStop(function (res : obj) {
			uni.uploadFile({
				// @ts-ignore
				url: `${uni.$baseUrl}/uploadTwo`,
				name: 'file',
				filePath: res.tempFilePath,
				header: {
					"Authorization": uni.getStorageSync('token')
				},
				success: (res) => {
					let date = JSON.parse(res.data).data
					sendConent({
						payload: {
							src: date.url,
							time: voiceTimer.value
						}
					}, 2)
				}
			})

		});
	}
	const touchmove = (e) => {
		clientY.moveY = e.changedTouches[0].clientY
	}
	const broadcast = (payload) => {
		// @ts-ignore
		innerAudioContext.src = `${uni.$baseUrl}/` + payload
		innerAudioContext.play()
	}
	//定位
	const getAddress = () => {
		// #ifdef APP-PLUS
		uni.chooseLocation({
			success: (res) => {
				console.log(res)
			}
		})
		// #endif
	}
	onShow(() => {
		let info = {
			crowd_id: gather.userinfo.crowd_id,
			userid: gather.selfInfo.userid,
			username: gather.selfInfo.username
		}
		socket.emit(`get_room_msg`, info)
		socket.emit('join', info)
	})
	const goPage = (type : Boolean, str = '') => {
		if (!type) return uni.navigateBack()
		uni.navigateTo({
			url: str
		})
	}
	onBackPress((e) => {
		socket.emit('leave', {
			crowd_id: gather.userinfo.crowd_id,
			userid: gather.selfInfo.userid,
			username: gather.selfInfo.username
		})
	})
	onUnload(() => {
		socket.removeListener('leave')
		socket.removeListener('get_room_msg')
	})
	onLoad(() => {
		getEmo(gather.emoji.swiperCurrent, 80)
		gather.userinfo = store.state.chatUser	//群信息
		//加入房间
		socket.on('join', (msg) => {

		})
		socket.on('send_room_msg', (msg) => {
			gather.messageList = [...gather.messageList, msg]
			setTimeout(() => {
				gather.scrollToView = 'ID' + (gather.messageList.length - 1)
			}, 100)
		})
		socket.on('get_room_msg', data => {
			gather.messageList = [...gather.messageList, ...data]
			setTimeout(() => {
				gather.scrollToView = 'ID' + (gather.messageList.length - 1)
			}, 100)
		})
	})
	//发送
	const send = () => {
		if (!gather.sendMsg) return
		sendConent({
			content: gather.sendMsg,
		}, 0)
	}
	const sendConent = (obj : obj, type : number = 0) => {
		let info = {
			...obj,
			type: type, //0文字 1图片 2音频 3视频
			userid: gather.selfInfo.userid,	//自己
			username: gather.selfInfo.username,
			crowd_id: gather.userinfo.crowd_id,//群id
			title: gather.userinfo.title,//群名
			handimg: gather.selfInfo.handimg
		}
		socket.emit('send_room_msg', info)
		gather.scrollAnimation = true
		voicePop.value = false
		gather.sendMsg = ''
	}
	const filterTimer = (time : number) => {
		if (time <= 5) return '10%'
		if (time > 5 && time <= 10) return '15%'
		if (time > 10 && time <= 20) return '20%'
		if (time > 20 && time <= 30) return '25%'
		return '30%'
	}
	const rtvVideo = (item) => {
		//判断是否结束
		if (!item.status && item.userid) return
		sendConent({
			content: '发送了一条视频通话',
			status: 1	//聊天存在 0不存在
		}, 3)
		goPlay(2)
	}
	const isNewMinute = computed(() => (timestamp) => {
		if(!timestamp) return false
		return (new Date().getTime() - new Date(timestamp).getTime()) > 180000
	})
	const goPlay = (palyerType : number) => {
		// #ifdef APP-PLUS
		uni.navigateTo({
			url: `/pages_home/crowd_live/index?palyerType=${palyerType}`
		})
		// #endif
		// #ifndef APP-PLUS
		uni.navigateTo({
			url: `/pages_home/crowd_live/live?palyerType=${palyerType}`
		})
		// #endif
	}
	const filterDate = computed(() => (item : any) => {
		return dateTime.timeago(new Date(item))
	})
</script>

<template>
	<view class="main psb flex flex-dir-c" @click="onPop">
		<view class="flex flex-ai-c flex-jc-sb f1 nav" style="padding: 0 10rpx;">
			<u-icon name="arrow-left" @click="goPage(false)" size="40rpx"></u-icon>
			<view>{{gather.userinfo.title}}</view>
			<u-icon name="list"
				@click="goPage(true,`/pages_new/crowdSetting/index?crowd_id=${gather.userinfo.crowd_id}&leaderid=${gather.userinfo.leaderid}`)"
				size="40rpx"></u-icon>
		</view>
		<!-- 聊天信息 -->
		<scroll-view class="scroll-view f1" scroll-y :scroll-with-animation="gather.scrollAnimation"
			:scroll-top="gather.scrollTop" :scroll-into-view="gather.scrollToView" @scrolltoupper="loadHistory">
			<view class="flex flex-jc-c loading" v-if="gather.isLoading">
				<u-loading mode="circle"></u-loading>
			</view>

			<block v-for="(item,index) in gather.messageList" :key="index">
				<view :id="'ID'+index">
					<view class="chat">
						<view style="margin: 20rpx 0;">
							<view class="chat-time" v-if="isNewMinute(item.time)">{{filterDate(item.time)}}</view>
						</view>
						<!-- 左边 -->
						<view class="flex flex-ai-c chat-list" v-if="item.userid != gather.selfInfo.userid">
							<view class="head-img">
								<image style="border: 0;" :src="item.handimg"></image>
							</view>
							<!-- 图片信息 -->
							<view class="chat-image" v-if="item.type === 1" @click="preview(item.content)">
								<image mode="aspectFill" :src="item.content"></image>
							</view>
							<!-- 文本信息 -->
							<view class="chat-msg" v-else-if="item.type === 0">
								<view>{{item.content}}</view>
							</view>
							<!-- 音频 -->
							<view v-else-if="item.type === 2" :style="{'width': filterTimer(item.payload.time)}"
								style="max-width: 30%;background: #fff;border-radius: 15rpx;height: 50rpx;"
								class="flex flex-ai-c" @click="broadcast(item.payload.src)">
								<view class="yuyin bci" style="width: 40rpx;height: 40rpx;"></view>{{item.payload.time}}
							</view>
							<view class="chat-msg" v-else-if="item.type === 3" @click="rtvVideo(item)">
								<view>{{item.status ? '发起了一条视频聊天' : '聊天已结束' }}</view>
							</view>
						</view>
						<!-- 右边 -->
						<view v-else class="flex flex-ai-c flex-jc-fe chat-list">
							<!-- 图片信息 -->
							<view class="chat-image" v-if="item.type === 1" @click="preview(item.content)">
								<image mode="aspectFill" :src="item.content"></image>
							</view>
							<!-- 文本信息 -->
							<view class="chat-msg" v-else-if="item.type === 0">
								<view>{{item.content}}</view>
							</view>
							<view v-else-if="item.type === 2" :style="{'width': filterTimer(item.payload.time)}"
								style="max-width: 30%;background: #fff;border-radius: 15rpx;height: 50rpx;"
								class="flex flex-ai-c" @click="broadcast(item.payload.src)">
								<view class="yuyin bci" style="width: 40rpx;height: 40rpx;"></view>{{item.payload.time}}
							</view>
							<view class="chat-msg" v-else-if="item.type === 3">
								<view>{{item.content}}</view>
							</view>
							<view class="head-img">
								<image style="border: 0;" :src="gather.selfInfo.handimg"></image>
							</view>
						</view>
					</view>
				</view>
			</block>
		</scroll-view>

		<!-- 底部菜单栏 -->
		<view style="position: relative;height: 170rpx;">
			<view class="menu flex flex-dir-c flex-jc-c">
				<view class="flex flex-ai-c" style="padding: 0 20rpx;">
					<u-input :cursor-spacing="20" placeholder="" :clearable="false" height="40rpx"
						v-model="gather.sendMsg" :custom-style="gather.inputStyle" type="textarea" />
					<view class="menu-send" @click="send">发送</view>
				</view>
				<view class="icon flex flex-jc-sb flex-ai-c">
					<view class="yy bci" @click.stop="onPop(1)"></view>
					<view class="pic bci"></view>
					<view class="xj bci" @click.stop="rtvVideo"></view>
					<view class="bq bci" @click.stop="onPop(4)"></view>
					<u-icon name="plus-circle" size="50" @click.stop="getAddress"></u-icon>
				</view>

			</view>
		</view>
		<!-- 表情包 -->
		<view class="pop" style="background: gainsboro;" v-if="emojiPop">
			<swiper :current="gather.emoji.swiperCurrent" @change="listSwitch" class="swiper" :duration="300">
				<swiper-item class="swiper-item" v-for="(item,index) in gather.emoji.swiperSize" :key='index'>
					<scroll-view style="height: 100%;" scroll-y>
						<view class="flex flex-wrap-w">
							<view class="emoji" v-for="(item2,index) in gather.emoji.list" :key="index">
								<view class="emoji-text" @click.stop="onEmoji(item2)">
									{{item2}}
								</view>
							</view>
						</view>
					</scroll-view>
				</swiper-item>
			</swiper>
		</view>
		<!-- 录音 -->
		<view class="pop" v-if="voicePop" @click.stop>
			<view class="sound flex flex-jc-c flex-ai-c flex-dir-c" @touchstart.stop="touchstart" @touchend="touchend"
				@touchmove="touchmove">
				<view style="margin-bottom: 20rpx;">{{voiceShow?voiceTimer:'按住录音'}}</view>
				<view class="sound-icon">
					<view class="yy bci"></view>
				</view>
			</view>
		</view>

		<view v-show="voiceShow" class="flex flex-ai-c flex-jc-c"
			style="height: 100%;width: 100%;position: fixed;top: 0;bottom: 0;background-color: rgba(0,0,0,0.3);z-index: 10;">
			<view class="voice_an">
				<view class="voice_an_icon">
					<view id="one" class="wave"></view>
					<view id="two" class="wave"></view>
					<view id="three" class="wave"></view>
					<view id="four" class="wave"></view>
					<view id="five" class="wave"></view>
					<view id="six" class="wave"></view>
					<view id="seven" class="wave"></view>
				</view>
				<view class="text">正在录音</view>
			</view>
		</view>

		<!-- 弹窗层 -->

	</view>
</template>

<style lang="scss" scoped>
	@import '../chat/index.scss';
</style>